#!/usr/bin/python3
# -*- encoding: utf-8 -*-
"""
@File    : drf.py
@Time    : 2022/6/1 14:44
@Author  : YangXin
@License : Copyright(C) 2022 忆享科技 All rights reserved
@Desc    :
"""
from blueapps.utils import get_client_by_request
from rest_framework.decorators import action
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import viewsets

from home_application.models import TaskRecord
from home_application.serializers import TaskRecordSerializer, TaskSerializer


def success(data, code=0, message='success', result=True):
    return Response({
        "code": code,
        "message": message,
        "result": result,
        "data": data
    })


def failed(code=0, message="error", result=False):
    return Response({
        "code": code,
        "message": message,
        "result": result,
        "data": None
    })


class BizAPIView(APIView):

    # 获取业务
    def get(self, request):
        client = get_client_by_request(request)
        kwargs = {
            "fields": [
                "bk_biz_id",
                "bk_biz_name"
            ],
            "page": {
                "start": 0,
                "limit": 200,
                "sort": ""
            }
        }
        res = client.cc.search_business(kwargs)
        if res.get("code") != 0:
            return failed(message=res.get("message", "error"))
        bizs = [
            {
                "id": item["bk_biz_id"],
                "name": item["bk_biz_name"],
            } for item in res["data"]["info"]
        ]
        return success({
            "count": res["data"]["count"],
            "info": bizs,
        })


class DataPageNumberPagination(PageNumberPagination):
    page_size = 10
    page_query_param = "page"
    page_size_query_param = "size"
    max_page_size = 1000

    def get_paginated_response(self, data):
        return Response({"count": self.page.paginator.count, "info": data})


class TplViewSet(viewsets.GenericViewSet):

    # 获取模板
    @action(detail=False, methods=["GET"])
    def get_tpl(self, request):
        client = get_client_by_request(request)
        kwargs = {
           "bk_biz_id": request.query_params.get("biz_id")
        }
        res = client.sops.get_template_list(kwargs)
        if res.get("code") != 0:
            return failed(message=res.get("message", "error"))
        tpl = [
            {
                "id": item["id"],
                "name": item["name"],
            } for item in res["data"]
        ]
        return success({
            "tpl": tpl
        })

    # 获取模板详情
    @action(detail=False, methods=["GET"])
    def get_tpl_info(self, request):
        client = get_client_by_request(request)
        kwargs = {
            "bk_biz_id": request.query_params.get("biz_id"),
            "template_id": request.query_params.get("tpl_id")
        }
        res = client.sops.get_template_info(kwargs)
        if res.get("code") != 0:
            return failed(message=res.get("message", "error"))
        # 字段类型 int、string
        return success({"fields": res["data"]["pipeline_tree"]["constants"]})


class ResponseMixin(object):
    def finalize_response(self, request, response, *args, **kwargs):
        if isinstance(response, Response):
            response.data = {
                "result": True,
                "data": response.data,
                "code": 0,
                "messages": "success",
            }
        return super(ResponseMixin, self).finalize_response(
            request, response, *args, **kwargs
        )


class TaskViewSet(ResponseMixin, viewsets.ModelViewSet):
    queryset = TaskRecord.objects.filter(is_deleted=False).order_by("-id")
    serializer_class = TaskRecordSerializer
    pagination_class = DataPageNumberPagination

    def get_serializer_class(self):
        if self.action == "create":
            return TaskSerializer
        return TaskRecordSerializer

    def retrieve(self, request, *args, **kwargs):
        obj = self.get_object()
        serializer = self.get_serializer(obj)
        data = serializer.data
        data.update({
            "tpl_name": obj.tpl_name,
            "task_url": obj.task_url
        })
        return Response(data)

